package com.swlz.service.impl;

import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.swlz.commons.PasswordUtil;
import com.swlz.dao.RoleDAO;
import com.swlz.dao.UserDAO;
import com.swlz.dto.UserFormDTO;
import com.swlz.dto.UserSearch;
import com.swlz.entity.Role;
import com.swlz.entity.User;
import com.swlz.exception.CodeException;
import com.swlz.service.UserService;
import com.swlz.vo.LoginUser;
import com.swlz.vo.PageVO;
import com.swlz.vo.UserVO;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;

/**
 * <pre>
 * - 
 * ClassName : com.swlz.service.impl.UserServiceImpl
 * Author : swlz
 * E-Mail : 2233875735@qq.com
 * Date : 2020年7月25日 上午10:42:29
 * Version : 1.0
 * Copyright 2020 swlz.top Inc. All rights reserved. 
 * Warning: this content is only for internal circulation of the company. 
 * It is forbidden to divulge it or use it for other commercial purposes.
 * </pre>
 **/
public class UserServiceImpl implements UserService {
	
	private static Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

	private UserDAO userDAO = new UserDAO();
	private RoleDAO roleDAO = new RoleDAO();

	@Override
	public List<User> list(int len) {
		try {
			return userDAO.selectByModel(null, 0, len);
		} catch (SQLException e) {
			throw new RuntimeException("获取用户列表失败", e);
		}
	}

	@Override
	public int delete(Long userId) {
		try {
			return userDAO.deleteById(userId);
		} catch (Exception ex) {
			throw new RuntimeException("删除用户失败", ex);
		}
	}

	@Override
	public int add(UserFormDTO user) {

		// if(user.getUserName()==null || user.getUserName().trim().equals("")){
		if (StrUtil.hasBlank(user.getUserName())) {
			throw new RuntimeException("用户名不能为空");
		}

		// if(user.getUserPassword()==null ||
		// user.getUserPassword().equals("")){
		if (StrUtil.hasEmpty(user.getUserPassword())) {
			throw new RuntimeException("密码不能为空");
		}

		if (existsUserName(user.getUserName())) {
			throw new RuntimeException("用户名已经存在");
		}

		String userSalt = UUID.randomUUID().toString().replace("-", "");
		String userPassword = PasswordUtil.encode(user.getUserPassword(), userSalt);

		User user1 = new User();

		// user1.setUserName(user.getUserName());
		// user1.setUserNickname(user.getUserNickname());
		// ...
		BeanUtil.copyProperties(user, user1);
		user1.setUserPassword(userPassword);
		user1.setUserSalt(userSalt);

		// 默认值的设置,最好可配置
		user1.setDeptId(1L);
		user1.setRoleId(1);
		user1.setUserScore(0);
		user1.setUserLevel(1);
		user1.setUserStatus(0);

		try {
			return userDAO.insert(user1);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new RuntimeException("保存用户数据失败", ex);
		}

	}

	@Override
	public boolean existsUserName(String userName) {
		User user = new User();
		user.setUserName(userName);
		try {
			userDAO.selectByModel(user);
			return true;
		} catch (SQLException e) {
			return false;
		}
	}


	@Override
	public User get(Long userId) {
		try {
			return userDAO.selectById(userId);
		} catch (Exception ex) {
			ex.printStackTrace();// 日志
			throw new RuntimeException("查询用户数据失败", ex);
		}
	}

	@Override
	public int update(User user) {
		try {
			user.setUserName(null);// 设置不需要修改的字段
			user.setCreateTime(null);
			user.setCreateUser(null);
			return userDAO.updateSelective(user);// 修改null的字段

			// User oldUser = userDAO.selectById(user.getUserId());
			// oldUser.setUserQq(user.getUserQq());
			// oldUser.setUserBrithdate(user.getUserBrithdate());
			// //...设置所有需要修改的字段
			// return userDAO.update(oldUser);

		} catch (Exception ex) {
			ex.printStackTrace();// 日志
			throw new RuntimeException("修改用户数据失败", ex);
		}

	}

	@Override
	public List<User> list(int current, int rowMax) {
		try {
			return userDAO.selectByModel(null, (current - 1) * rowMax, rowMax);
		} catch (SQLException e) {
			e.printStackTrace();// 日志
			throw new RuntimeException("获取用户分页数据失败", e);
		}
	}



	@Override
	public PageVO<UserVO> page(UserSearch search) {
		try {
			PageVO<UserVO> page = new PageVO<UserVO>(userDAO.count(search), search.getPageNumber(),
					search.getPageSize());
			return page.setList(userDAO.select(search, page.getOffset(), page.getRowMax()));
		} catch (SQLException e) {
			e.printStackTrace();// 日志
			throw new RuntimeException("获取用户分页数据失败", e);
		}
	}


	@Override
	public LoginUser login(String userName, String userPwd) throws CodeException {
		LoginUser user = new LoginUser();

		User u = new User();
		u.setUserName(userName);
		try {
			u = userDAO.selectByModel(u);
		} catch (Exception ex) {
			throw new CodeException(1,"用户不存在", ex);
		}
		if (!u.getUserPassword().equals(PasswordUtil.encode(userPwd, u.getUserSalt()))) {
			throw new CodeException(2,"密码错误");
		}

		if (u.getUserStatus().equals(1)) {
			throw new CodeException(3,"用户被锁定");
		}

		BeanUtil.copyProperties(u, user);
		Role role;
		try {
			role = roleDAO.selectById(u.getRoleId());
		} catch (SQLException e) {
			throw new CodeException(1,"用户不存在", e);
		}
		BeanUtil.copyProperties(role, user);
		System.out.println(u);
		return user;
	}

}
